package cn.gailvlun.gll.util;

import org.joda.time.DateTime;

import java.util.Date;

import cn.gailvlun.gll.Constants;
import cn.gailvlun.gll.db.NetMigration;
import cn.gailvlun.gll.db.NetModule;
import cn.gailvlun.gll.net.base.Profile;
import cn.gailvlun.gll.net.base.RefreshTokenRes;
import io.realm.Realm;
import io.realm.RealmConfiguration;



public class ProfileUtil {

    private static Integer userId;
    private static String token;
    private static RealmConfiguration mConfiguration;

    public static Integer getUserId() {
        if (userId == null) {
            synchronized (ProfileUtil.class) {
                if (userId == null) {
                    Integer userId = SPUtil.getInteger(SPUtil.GLOBAL, "userId");
                    if (userId == null || userId == -1) {
                        return null;
                    }
                    ProfileUtil.userId = userId;
                }
            }
        }
        return userId;
    }

    private static RealmConfiguration getConfiguration() {
        if (mConfiguration == null) {
            synchronized (ProfileUtil.class) {
                if (mConfiguration == null) {
                    mConfiguration = new RealmConfiguration.Builder()
                            .modules(Realm.getDefaultModule(), new NetModule())
                            .name("base-" + getUserId() + ".realm")
                            .schemaVersion(5)
                            .migration(new NetMigration())
                            .build();
                }
            }
        }
        return mConfiguration;
    }

    public static Profile getProfile() {
        getUserId();
        if (userId == null) {
            return null;
        }
        LogUtil.d("get, thread: " + Thread.currentThread().getName());
        Realm realm = Realm.getInstance(getConfiguration());
        Profile profile = realm.where(Profile.class).findFirst();
        Profile returnProfile = null;
        if (profile != null) {
            returnProfile = realm.copyFromRealm(profile);
        }
        realm.close();
        return returnProfile;
    }

    public static String getToken() {
        if (token == null) {
            Realm realm = Realm.getInstance(getConfiguration());
            Profile profile = realm.where(Profile.class).findFirst();
            if (profile == null) {
                return null;
            }
            token = profile.getToken();
        }
        return token;
    }

    public static void refresh(RefreshTokenRes refreshTokenRes) {
        if (refreshTokenRes != null) {
            token = refreshTokenRes.getToken();

            Realm realm = Realm.getInstance(getConfiguration());
            Profile profile = realm.where(Profile.class).findFirst();
            if (profile != null) {
                realm.beginTransaction();
                profile.setToken(refreshTokenRes.getToken());
                profile.setRefresh_token(refreshTokenRes.getRefresh_token());
                profile.setActivated(refreshTokenRes.isActivated());
                
                profile.setExpiredTime(DateTime.now().plus(Constants.expiredDuration).toDate());
                realm.insertOrUpdate(profile);
                realm.commitTransaction();
                realm.close();
                LogUtil.d("save: thread: " + Thread.currentThread().getName());
            }
        }
    }

    public static void save(Profile profile) {
        SPUtil.put(SPUtil.GLOBAL, "userId", profile.getId());

        
        profile.setExpiredTime(DateTime.now().plus(Constants.expiredDuration).toDate());
        Realm realm = Realm.getInstance(getConfiguration());
        realm.beginTransaction();
        realm.delete(Profile.class);
        realm.insertOrUpdate(profile);
        realm.commitTransaction();
        realm.close();
    }

    public static void modify(Profile profile) {
        Realm realm = Realm.getInstance(getConfiguration());
        Profile savedProfile = getProfile();

        if (savedProfile != null) {
            realm.beginTransaction();
            savedProfile.setAvatar(profile.getAvatar());
            savedProfile.setName(profile.getName());
            savedProfile.setDescription(profile.getDescription());
            savedProfile.setBirthday(profile.getBirthday());
            savedProfile.setGender(profile.isGender());
            savedProfile.setIs_profile_public(profile.getIs_profile_public());
            savedProfile.setCity(profile.getCity());
            realm.insertOrUpdate(savedProfile);
            realm.commitTransaction();
        }
        realm.close();
    }

    
    public static boolean isTokenExpired() {
        Profile profile = getProfile();
        if (profile != null) {
            Date expiredTime = profile.getExpiredTime();
            if (System.currentTimeMillis() < expiredTime.getTime()) {
                
                return false;
            }
        }
        
        return true;
    }

    public static void logOut() {
        SPUtil.put(SPUtil.GLOBAL, "userId", -1);

        userId = null;
        token = null;
        mConfiguration = null;
    }

    public static void setActivated(Profile profile) {
        SPUtil.put(SPUtil.GLOBAL, "userId", profile.getId());

        
        Realm realm = Realm.getInstance(getConfiguration());
        realm.beginTransaction();
        profile.setExpiredTime(DateTime.now().plus(Constants.expiredDuration).toDate());
        profile.setActivated(true);
        realm.insertOrUpdate(profile);
        realm.commitTransaction();
        realm.close();
    }

    public static void updateProfileInfoVisible(boolean visibility) {
        Realm instance = Realm.getInstance(getConfiguration());
        Profile profile = getProfile();
        if (profile != null) {
            instance.beginTransaction();
            profile.setIs_profile_public(visibility);
            instance.insertOrUpdate(profile);
            instance.commitTransaction();
        }
        instance.close();

    }
}
